package music;

import java.io.File;
import java.util.Scanner;

/**
 * @author xiakai
 * @create 2020-05-23 19:34
 */
public class CleanMusicByName {

    public static void main(String[] args) {

        System.out.println("请输入目录");
        Scanner cs = new Scanner(System.in);
        String musicPath = cs.nextLine();

        if (musicPath == null || musicPath.length() == 0) {
            System.out.println("非法");
            return;
        }
        File[] musicList = new File(musicPath).listFiles();

        for (File music : musicList) {
            if (music.isDirectory()) {
                continue;
            }
            String name = music.getName();
//            System.out.println(name);
            if (name.equals("desktop.ini")) {
                if (music.delete()) {
                    System.out.println("desktop.ini已删除");
                } else {
                    System.out.println("desktop.ini 无法删除，是否跳过(输入1)");
                    if (new Scanner(System.in).nextInt() == 1) {
                        continue;
                    } else {
                        System.out.println("已终止");
                        return;
                    }
                }
            }
            String artist;
            try {
                artist = name.substring(0, name.indexOf(" - "));
            } catch (StringIndexOutOfBoundsException e) {
                System.out.println(name + " 文件名错误，估计是缺少‘-’");
                return;
            }

            int i = artist.indexOf('(');
            int j = artist.indexOf('／');

            if (i >= 0) {
                if (j >= 0) {
                    artist = artist.substring(0, Math.min(i, j));
                } else {
                    artist = artist.substring(0, i);
                }
            } else if (j >= 0) {
                artist = artist.substring(0, j);
            }


            File artistDir = new File(musicPath, artist);
            if (!artistDir.exists()) {
                artistDir.mkdirs();
            }
            File newFile = new File(artistDir, name);
            if (newFile.exists()) {
                System.out.println(name + " 已存在");
            } else {
                music.renameTo(newFile);
                System.out.println(name + " 移入：" + artistDir.getName());
            }
        }
        System.out.println("end!");
    }

}
